#include "InnerTemperatureMonitor.h"

#include <charconv>

#include "CommandParser.h"

InnerTemperatureMonitor::InnerTemperatureMonitor(const ExtendDeviceType& deviceType): ExtendDevice(mdummyChannel, deviceType, ""), mtemperatureDevice("/sys/class/hwmon/hwmon0/temp1_input", O_RDONLY | O_CLOEXEC)
, mdummyChannel(-1, mtemperatureDevice), mcommandParser(CommandParserSingleton::instance()) {

}


bool InnerTemperatureMonitor::updateInformation() {

    return true;
}



bool InnerTemperatureMonitor::activeUpdateInformation() {
    bool updateResult = true;
    char buffer[STRING_BUFFER_SIZE];

    mtemperatureDevice.close();
    mtemperatureDevice.reopen();
    ssize_t  length = ::read(mtemperatureDevice.getDeviceFd(), buffer, sizeof buffer);
    if(0 < length) {
        int32_t tempValue;
        std::from_chars(buffer, buffer + length, tempValue);
        mtemperature.first = tempValue / 1000.0f;
        mtemperature.second.resize(64);
        tempValue = snprintf(mtemperature.second.data(), mtemperature.second.size(), "%.2f", mtemperature.first);
        mtemperature.second.resize(tempValue);

        if (mtemperature.first > mthreshold.first){
            if (!msent){
                mcommandParser.sendTemperatureAlarm(mthreshold.second);
            }
            ++msent;
        } else {
            msent = 0;
        }

    } else {
        updateResult = false;
    }
//    LOG_DEDUG("DeviceFd:%d, readed:%d",mtemperatureDevice.getDeviceFd(), length);

    return updateResult;
}


